package com.zzx.test.thread.juc;

import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @ClassName: ReentrantLockTest
 * @Description: 可重入锁测试类1
 * @Author zhouzhixin
 * @Date 2021/12/2
 * @Version 1.0
 */
public class ReentrantLockTest1 {

    public static void main(String[] args) {
        test2();
    }

    private static void test1() {
        LockTest1 lockTest1 = new LockTest1();
        ThreadPoolExecutor executor = new ThreadPoolExecutor(5, 10, 5L
                , TimeUnit.SECONDS, new LinkedBlockingQueue<>(5), Executors.defaultThreadFactory()
                , new ThreadPoolExecutor.DiscardPolicy());
        for (int i = 0; i < 5; i++) {
            executor.execute(lockTest1::lockTest1);
        }
        executor.shutdown();
    }

    private static void test2() {
        LockTest1 lockTest1 = new LockTest1();
        LockTest1 lockTest2 = new LockTest1();
        LockTest1 lockTest3 = new LockTest1();
        new Thread(lockTest1::lockTest1, "A").start();
        new Thread(lockTest2::lockTest1, "B").start();
        new Thread(lockTest3::lockTest1, "C").start();
    }

}

class LockTest1 {

    ReentrantLock lock = new ReentrantLock(true);

    public void lockTest1() {
        try {
            lock.lock();
            System.out.println(Thread.currentThread().getName() + " in");
            TimeUnit.MILLISECONDS.sleep(500);
            System.out.println(Thread.currentThread().getName() + " out");
            TimeUnit.MILLISECONDS.sleep(500);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

}
